<template>
  <iss-library-form-designer
      clearable
      generate-code
      generate-json
      preview
      import-json
      :custom-component-list="customComponentList"
  ></iss-library-form-designer>
</template>
<script>
import Vue from 'vue'

export default {
  data() {
    return {
      customFields: [],
      globalConfig: {},
      fieldConfig: [],
      customComponentList: [],
      componentConfig: {
        name: '脚手架测试组件',
        icon: '',
        showDefaultValue: true,
        notFormItem: false
      }
    }
  },
  async created() {
    this.customComponentList = await this.getCustomComponentList()
  },
  methods: {
    // 解析umd文件
    async loadComponent(address) {
      let module = await window.System.import(address)
      return module
    },
    getCustomComponentList() {
      // 打包后的文件
      const files = require.context('../../public/dist/', false, /.js$/).keys()
      // todo 支持多个自定义组件.目前是一个文件
      let list = []
      files.forEach(async item => {
        const name = item.split('.')[1].split('/')[1]
        const content =
            location.origin + location.pathname + '/dist/' + name + '.umd.min.js'
        const module = await this.loadComponent(content)
        // 注册组件
        const componentNames = Object.keys(module.default).filter(
            item => item !== 'config'
        )
        componentNames.forEach(name => {
          Vue.component(name, module[name])
        })
        // 取配置文件里的配置
        let jsonSchema = module['config'].componentConfig
        jsonSchema.customType = 'sourceCode'
        jsonSchema.disableFlag = false
        // 组件名称
        this.componentConfig.name = jsonSchema.name
        list.push({
          name,
          jsonSchema,
          content,
          componentConfig: this.componentConfig,
          componentMap: module['config'].componentMap
        })
      })
      return list
    }
  }
}
</script>
